import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { EventProvider } from '../../providers/event/event';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { Network } from '@ionic-native/network';
import { LoadingController, Loading } from 'ionic-angular';
import { WechatProvider } from '../../providers/wechat/wechat';
declare let cordova: any;
/**
 * Generated class for the ChargingAccountPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-charging-account',
  templateUrl: 'charging-account.html',
})
export class ChargingAccountPage {
  //支付类型
  paytype: any;

  //支付金额
  pay_money;

  member_id: any;

  // 用户信息
  userInfo: login_info = new login_info();

  constructor(
    public navCtrl: NavController,
    public viewCtrl: ViewController,
    public navParams: NavParams,
    public http: HttpProvider,
    private network: Network,
    public storage: StorageProvider,
    public dialog: DialogProvider,
    public eventsPvd: EventProvider,
    public user: UserInfoProvider,
    public loadingCtrl: LoadingController,
    public wx: WechatProvider) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ChargingAccountPage');
    this.member_id = this.navParams.get('member_id');
    this.userInfo = this.user.getuserInfo();
    this.member_id = this.userInfo.member_id;
    // this.storage.getStorage("login_info").then(res => {
    //   console.log(res);
    //   if (res != undefined) {
    //     this.userInfo = res;
    //     this.member_id = res['member_id'];
    //   }
    // });
  }

  changPay_money(data) {
    this.pay_money = data;
  }

  async pay() {
    if (this.pay_money <= 0) {
      this.dialog.showAlert('输入金额不正确', '');
      return;
    }
    if (!this.pay_money) {
      this.dialog.showAlert('请输入充值金额', '');
      return;
    }
    //判断是否有值，为空就假
    if (!this.paytype) {
      this.dialog.showAlert('请选择支付方式', '');
      return;
    }

    let wechatIsInstalled = true;
    if (this.paytype === '1') {
       this.wx.isInstalled().then( (installed) => {
        wechatIsInstalled = true;
        // this.dialog.showAlert('安装', JSON.stringify(installed));
      }, (reason) => {
        wechatIsInstalled = false;
        //  this.dialog.showAlert('未安装', JSON.stringify(reason));
      });
    }

    if (this.network.type === 'none' || this.network.type === '2g') {
      this.dialog.showAlert('网络未连接，无法充值。', '');
      return;
    }

    if (!wechatIsInstalled) {
      this.dialog.showAlert('没有检测到微信', '');
    }
    let loading = this.loadingCtrl.create({
      content: '支付中...'
    });
    loading.present();
    const a = {
      recharge_at: new Date().getTime().toString().slice(0, 10),
      member_id: this.member_id,
      money: this.pay_money,
      payment_id: this.paytype,
      states: 0
    }

    // a.money=0.01;
    const res = await this.http.postJson('', 'member/memberr/create', a, '')
      .then(res => {
        loading.dismiss();
        if (res['status'] == 200) {
          if (this.paytype === '2') {
            this.alipay(res['data'][0]);
          }

          if (this.paytype === '1') {
            this.wechat(res['data'][0]);
          }

          // this.eventsPvd.sendEvents(this.eventsPvd.EVENT_CENTER, {});
          // this.navCtrl.pop();
          // this.navCtrl.pop();
          // this.userInfo.balance = parseFloat(this.userInfo.balance) + this.pay_money;
          // this.storage.saveStorage("login_info", this.userInfo);

        } else {
          this.dialog.showAlert(res['message'], '');
        }
      });
  }

  async login() {
    await this.storage.getStorage("login_info").then(res => {
      if (res != undefined) {
        this.userInfo = res;
      }
    });
    const res = await this.http.postJson('', 'member/member/view?id=' + this.userInfo.member_id, {}, '')
      .then(res => {
        if (res['status'] == 200) {
          res['data']['password'] = this.userInfo.password;
          res['data']['isAutomaticLogon'] = this.userInfo.isAutomaticLogon;
          this.userInfo = res['data'];
          console.log(this.userInfo);
          this.user.setuserInfo(this.userInfo);
          // this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
          // this.navCtrl.push('CenterPage');
        }
      });
    return;
  }

  async alipay(payInfo) {
    cordova.plugins.alipay.payment(payInfo,
      (success) => {
        this.dialog.showAlert('支付成功', '');
        this.login();

        const index = this.viewCtrl.index;
        for (let i = index; i > 0; i--) {
          this.navCtrl.remove(i);
        }
        this.navCtrl.parent.select(2);
        //      this.navCtrl.setRoot('CenterPage');
      },
      (error) => {
        //      this.dialog.showAlert('支付失败', '');
      });
    return;
  }

  async wechat(payInfo) {
    // this.dialog.showAlert('payInfo', JSON.stringify(payInfo));
    let params = {
      mch_id: payInfo.partnerid, // merchant id
      prepay_id: payInfo.prepayid, // prepay id
      nonce: payInfo.noncestr, // nonce
      timestamp: payInfo.timestamp + "", // timestamp
      sign: payInfo.sign, // signed string
      appid: 'wx541309d09585de38'
    };
    // this.dialog.showAlert('params', JSON.stringify(params));
    this.wx.sendPaymentRequest(params).then((res) => {
      this.login();

      const index = this.viewCtrl.index;
      for (let i = index; i > 0; i--) {
        this.navCtrl.remove(i);
      }
      this.navCtrl.parent.select(2);
      //      this.navCtrl.setRoot('CenterPage');
    }, (error) => {
      //  this.dialog.showAlert('支付失败', error);
    });

    return;

  }


}

export class login_info {
  member_id: any;
  nickname: any;
  phone: any;
  balance: any;
  local_balance: any;
  member_state: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  is_del: any;
  password: any;
  file_type_id: any;
  access_token: any;
  isAutomaticLogon: any;
}
